package antidestiny.java2dex.file;


import android.os.Bundle;
import android.support.annotation.NonNull;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import antidestiny.java2dex.Jing;
import antidestiny.utilib.Aide;
import antidestiny.utilib.io.FileUtils;

/**
 * Created by Hero on 2016/12/30.
 */

public class FileConstructor {


    /**
     * @return 创建好:Jing.RESULT_OK，未知原因:ing.UNKOWN_ERROR，文件已存在:Jing.FILE_EXISTED，母文件夹不存在返回Jing.PARENT_DIR_NOT_EXIST，非法字符返回Jing.ILLEGAL_CHAR
     */
    public int construct(int type, File file, File srcDir) throws IOException {
        String fileName = file.getName();
        File dirFile = file.getParentFile();
        if (type == Jing.TYPE_DIR) return createDir(fileName, dirFile);

        int indexOfDot = fileName.lastIndexOf('.');
        String name = fileName.substring(Jing.UNKOWN_ERROR, indexOfDot);
        String postFix = fileName.substring(indexOfDot + 1, fileName.length());
        if (postFix.equalsIgnoreCase("java") && type == Jing.TYPE_CLASS_FILE && fileName.length() > 0 && srcDir != null)
            return createClass(name, fileName, dirFile, srcDir);
        if (postFix.equalsIgnoreCase("java") && type == Jing.TYPE_JAVA_FILE && fileName.length() > 0 && srcDir != null)
            return createJava(fileName, dirFile, srcDir);
        return createEmptyFile(fileName, dirFile);
    }

    private int createDir(String filename, File dir) {
        if (!dir.exists()) return Jing.PARENT_DIR_NOT_EXIST;
        File toMk = new File(dir.getAbsolutePath() + '/' + filename);
        if (toMk.exists()) return Jing.FILE_EXISTED;
        boolean result = toMk.mkdir();
        if (!result) return Jing.UNKOWN_ERROR;
        return Jing.RESULT_OK;
    }

    private int createClass(String filename, String className, File dir, File srcDir) throws IOException {
        int result = createJava(filename, dir, srcDir);
        if (result != Jing.RESULT_OK) return result;
        File classFile = new File(dir.getAbsolutePath() + '/' + filename);
        FileWriter writer = null;
        try {
            writer = new FileWriter(classFile, true);
            writer.write("\n\n+public class " + className + " {\n}\n");
        } finally {
            if (writer != null) try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Jing.RESULT_OK;
    }

    private int createJava(String filename, File dir, File srcDir) throws IOException {
        if (filename.contains(".") || dir.getAbsolutePath().contains(".")) return Jing.ILLEGAL_CHAR;
        int result = createEmptyFile(filename, dir);
        if (result != Jing.RESULT_OK) return result;
        File java = new File(dir.getAbsolutePath() + '/' + filename);
        String packageStr = getPackage(java, srcDir);
        FileWriter writer = null;
        try {
            writer = new FileWriter(java, false);
            writer.write(packageStr + '\n');
            writer.close();
        } finally {
            if (writer != null) try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Jing.RESULT_OK;
    }


    public class TaskInfo {
        TaskInfo(int result){
            this.result=result;
        }
        TaskInfo( int result,File... files2open) {
            filesToOpen.addAll(Arrays.asList(files2open));
            this.result = result;
        }

        public ArrayList<File> filesToOpen=new ArrayList<>();
        public int result;
    }

    /**
     * 创建工程文件
     * @throws IOException
     */
    public TaskInfo createProject(String projectName, String packageStr, File dir) throws IOException {
        File srcDir = new File(dir.getAbsolutePath() + '/' + projectName + "/src");
        File deepDir = new File(srcDir.getAbsolutePath() + '/' + packageStr.replaceAll("\\.", "/"));
        File mainClassFile = new File(deepDir.getAbsolutePath() + "/Main.java");
        File proFile = new File(dir.getAbsolutePath() + '/' + projectName + '/' + projectName + Jing.PROJECT_POSTFIX);

        //创建包名所代表的目录
        boolean mkDirResult = deepDir.mkdirs();
        if (!mkDirResult) return new TaskInfo( Jing.UNKOWN_ERROR);

        int createProResult = createEmptyFile(proFile.getName(), proFile.getParentFile());
        if (createProResult != 1) return new TaskInfo(createProResult) ;
        //创建第一个java文件
        int createMainResult = createEmptyFile("Main.java", deepDir);
        if (createMainResult != 1) return new TaskInfo(createMainResult);


        FileWriter writer = null;
        try {
            writer = new FileWriter(proFile, false);
            writer.write("CreatedTimeMillis: " + System.currentTimeMillis()+'\n');
            writer.write(packageStr);
            writer.flush();
        } finally {

            try {
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //写helloworld
        try {
            writer = new FileWriter(mainClassFile, false);
            writer.write("package " + packageStr + ";\n\npublic class Main{\n   public static void main(String[] args){\n" +
                    "       System.out.println(\"hello world!\");\n   }\n}\n");
            writer.flush();
        } finally {
            try {
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return new TaskInfo(Jing.RESULT_OK,mainClassFile,proFile);
    }


    private int createEmptyFile(String filename, File dir) throws IOException {
        Aide.t("创建空文件：filename："+filename+"\ndir:"+dir);
        if (!dir.exists()) return Jing.PARENT_DIR_NOT_EXIST;
        File file = new File(dir.getAbsolutePath() + '/' + filename);
        if (file.exists()) return Jing.FILE_EXISTED;
        boolean result = file.createNewFile();
        if (!result) return Jing.UNKOWN_ERROR;
        return Jing.RESULT_OK;
    }

    /**
     * 获得（java）文件的包名
     * @param file java文件
     * @param srcDir 源代码主文件夹
     * @return 包名
     */
    private String getPackage(File file, File srcDir) {
        String result = FileUtils.getSubPath(file, srcDir);
        if (result == null) return "";
        result = result.replaceAll("/", ".");
        return "package " + result + ';';
    }

    public File getSrcDir(@NonNull File proFile) {
        return new File(proFile.getParentFile() + "/src");
    }


}
